﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Web;
using System.Web.Http;

namespace Pay.Token.Controllers
{
    [Authorize]
    public class BaseController : ApiController {
        /// <summary>
        /// 验证返回的错误提示
        /// </summary>
        public string ModelError {
            get {
                StringBuilder sb = new StringBuilder();
                foreach (var item in ModelState.Values) {
                    foreach (var er in item.Errors) {
                        if (!string.IsNullOrEmpty(er.ErrorMessage))
                            sb.Append(er.ErrorMessage + ",");
                        else
                            sb.Append(er.Exception.Message + ",");
                    }
                }
                return sb.ToString().TrimEnd(',');
            }
        }
        private long _user_id = 0;
        /// <summary>
        /// 登录用户ID
        /// </summary>
        protected long UserId {
            get {
                if (_user_id == 0 && User.Identity.IsAuthenticated) {
                    var identity = (User.Identity as ClaimsIdentity);
                    _user_id = long.Parse(identity.FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value);
                }
                return _user_id;
            }
        }
        private string _merchantNo = string.Empty;
        /// <summary>
        /// 登录商户号
        /// </summary>
        protected string MerchantNo {
            get {
                if (_merchantNo == string.Empty && User.Identity.IsAuthenticated) {
                    var identity = (User.Identity as ClaimsIdentity);
                    if (identity.HasClaim(c => c.Type == ClaimTypes.Actor))
                        _merchantNo = identity.FindFirst(c => c.Type == ClaimTypes.Actor).Value;
                }
                return _merchantNo;
            }
        }
        /// <summary>
        /// 获取以JSON（key:value)）的单参值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parameterName"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        protected T GetJsonValue<T>(string parameterName, JObject val) {
            if (val.HasValues) return val.GetValue(parameterName).ToObject<T>();
            return default(T);
        }

        /// <summary>
        /// 获取表单提交来的KEY=Value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parameterName"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        protected T GetPostValue<T>(string parameterName, T val) {
            if (val != null) return val;
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象            
            string value = request.Form[parameterName];

            Type type = typeof(T);
            object result;
            try {
                if (type.IsEnum)
                    result = (T)Enum.Parse(type, value, true);
                else if (type == typeof(Guid) || type == typeof(Guid?)) {
                    if (type == typeof(Guid))
                        result = new Guid(value);
                    else
                        if (!string.IsNullOrEmpty(value)) result = new Guid(value);
                    else result = null;
                } else {
                    if (IsNullableType(type))
                        result = Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
                    else
                        result = Convert.ChangeType(value, type);
                }
            } catch {
                result = default(T);
            }
            return (T)result;
        }
        /// <summary>
        /// 获取表单提交来的KEY=Value
        /// </summary>
        /// <returns>The post value.</returns>
        /// <param name="parameterName">Parameter name.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        protected T GetPostValue<T>(string parameterName) {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            HttpRequestBase request = context.Request;//定义传统request对象            
            string value = request.Form[parameterName];

            Type type = typeof(T);
            object result;
            try {
                if (type.IsEnum)
                    result = (T)Enum.Parse(type, value, true);
                else if (type == typeof(Guid) || type == typeof(Guid?)) {
                    if (type == typeof(Guid))
                        result = new Guid(value);
                    else
                        if (!string.IsNullOrEmpty(value)) result = new Guid(value);
                    else result = null;
                } else {
                    if (IsNullableType(type))
                        result = Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
                    else
                        result = Convert.ChangeType(value, type);
                }
            } catch {
                result = default(T);
            }
            return (T)result;
        }
        /// <summary>
        /// 判断是否是Nullable类型数据
        /// </summary>
        /// <param name="theType"></param>
        /// <returns></returns>
        protected bool IsNullableType(Type theType) {
            return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
        }
    }
}
